<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Classe controller che si occupa dell'installazione/disinstallazione del
 * plugin
 *
 * @author andrea
 */
class CInstallation_vidwiz extends Controller_vidwiz{

    /**
     * Installa la parte del plugin relativa ai video
     */
    public function installVideos(){
        $MVideos = USingleton_vidwiz::getInstances("MVideos_vidwiz");
        $drop = $MVideos->dropTable($MVideos->getInstallationTableName());
        $create = $MVideos->createQuery($MVideos->getInstallationTableName(),$MVideos->getInstallationFields());
        $MVideos->executeQuery($drop);
        $MVideos->executeQuery($create);
    }
    
    /**
     * Installa la parte del plugin relativa alla gestione del palinsesto
     */
    public function installPalinsesto(){
        $MPal = USingleton_vidwiz::getInstances("MPalinsesto_vidwiz");
        $drop = $MPal->dropTable($MPal->getInstallationTableName());
        $create = $MPal->createQuery($MPal->getInstallationTableName(),$MPal->getInstallationFields());
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $MPal->executeQuery($drop);
        $MPal->executeQuery($create);   
    }
    
    public function installContests(){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $MContest = USingleton_vidwiz::getInstances("MContests_vidwiz");
        $MPartecipations = USingleton_vidwiz::getInstances("MPartecipations_vidwiz");
        $drop = $MContest->dropTable($MContest->getInstallationTableName());
        $create = $MContest->createQuery($MContest->getInstallationTableName(),$MContest->getInstallationFields());
        
        $MContest->executeQuery($drop);
        $MContest->executeQuery($create);
        $drop = $MPartecipations->dropTable($MPartecipations->getInstallationTableName());
        $create = $MPartecipations->createQuery($MPartecipations->getInstallationTableName(),$MPartecipations->getInstallationFields());
        $MContest->executeQuery($drop);
        $MContest->executeQuery($create);
    }
    
    public function installScores(){
        $MScore = USingleton_vidwiz::getInstances("MScores_vidwiz");
        $drop = $MScore->dropTable($MScore->getInstallationTableName());
        $create = $MScore->createQuery($MScore->getInstallationTableName(),$MScore->getInstallationFields());
        $MScore->executeQuery($drop);
        $MScore->executeQuery($create);
    }
    
    public function createUPVCP(){
        $this->createUsers();
        $this->createPalinsestoPage();
        $this->createVideoCategory();
        $this->createCategories();
        $this->createMenu();
    }
    
    /**
     * Crea la page che contiene il palinsesto (lato utente)
     */
    public function createPalinsestoPage(){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $page = array();
        $page['post_title'] = "Palinsesto";
        $page['post_content'] = "[vidwiz-palinsesto]";
        $page['post_status'] = 'publish';
        $page['post_type'] = 'page';
        $page['comment_status'] = 'closed';
        $page['ping_status'] = 'closed';
        $page['post_category'] = array(1); // 
        $pageId = wp_insert_post( $page );
        update_option('page_on_front',$pageId);
        update_option('show_on_front','page');
    }
    
    public function createVideoCategory(){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $cat = array(
          'cat_name' => "video",
          'category_description' => "",
          'category_nicename' => "Videos",
                );
        wp_insert_category($cat);     
        $catid = get_cat_ID("video");
        add_option('vidwiz_video_category',$catid);
        update_option('vidwiz_video_category',$catid);
            }
    
    public function exampleData(){
        global $config; 
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $dirs = $config['exampledataSubdirs'];
        if(!is_dir($config['basedir_videos']))
            mkdir($config['basedir_videos']);
        foreach($dirs as $value){
                $this->installData($value['dir'],get_cat_ID($value['catname']));
        }
    }
    
    public function installData($dir,$cat){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $CVideo = USingleton_vidwiz::getInstances("CVideos_vidwiz");
        $EVideos  = USingleton_vidwiz::getInstances("EVideos_vidwiz");
        $MVideos = USingleton_vidwiz::getInstances("MVideos_vidwiz");
        global $config; 
        $handle = opendir($config['exampledatadir'].$dir);
        $i = 0;
        while (false != ($file = readdir($handle))) {
            
            if ($file != "." && $file != ".." && $file !=".directory") {
                $filedir = $config['exampledatadir'].$dir;
                $rand1a = rand(0,3);
                $rand1b = rand(0,3);
                $rand1c = rand(0,3);
                $user = rand(0,10);
                $position = $this->moveFileInstallation($filedir,$file,$config['users'][(int)$user]);
                $fields = array(
                    "file_position" => $position,
                    "description"   => $config['descriptions'][(int)$rand1a],
                    "title"         => "Video".(string)$i,
                    "metatags"      => "meta".(string)$rand1a.",meta".(string)$rand1b.",meta".(string)$rand1c,
                    "category"      => (string)$cat,
                    "publisher_username" => $config['users'][(int)$user],
                    "converted" => "FALSE",
                    "thumb" => ""
                        );
                $VideoData = $EVideos->generateObject($fields);
                $insert = $MVideos->insertQuery($VideoData);
                
                $MVideos->executeQuery($insert);
                $i=$i+1;
                }
        }
        closedir($handle);
    }
        /**
     * Sposta il file nella cartella passata
     * @param string $uploadDir la cartella nella quale bisogna spostare il file
     * @param string $filename il nome del file da spostare e rinominare
     * @return bool il nome del file se non ci sono errori, false in caso di errori 
     */
    public function moveFileInstallation($filedir,$filename,$username){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $check = USingleton_vidwiz::getInstances("UChecks_vidwiz");
        $model = USingleton_vidwiz::getInstances("Model_vidwiz");
        $file = $model->getFileInfo($filedir.$filename);
        global $config;
        
        $UPLOAD_BASE_DIR = $config['basedir_videos'].$username;
        $UPLOAD_DIR= $UPLOAD_BASE_DIR."/videos/";
        if(!is_dir($UPLOAD_BASE_DIR)){
                $model->createDir($UPLOAD_BASE_DIR);}
        if(!is_dir($UPLOAD_DIR) && !is_dir($UPLOAD_DIR."toConvert/")){
                $model->createDir($UPLOAD_DIR);
                $model->createDir($UPLOAD_DIR."toConvert/");
                }
        if($file!=false){
            $samename = true;
            $n=0;
            while($samename==true){
                $file = $model->renameFile($file);
                $samename = $check->check_samename($file['name'],$UPLOAD_DIR);
                }
            rename($file['dirname']."/".$file['basename'], $UPLOAD_DIR."toConvert/".$file['name'].$file['extension']);
            ;
            return str_replace($config['basedir'], "", $UPLOAD_DIR."toConvert/".$file['name'].$file['extension']);
            }
        return false;
    }
    
    public function createCategories(){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $model = USingleton_vidwiz::getInstances("Model_vidwiz");
        global $config;
        $terms = $config['terms'];
        foreach($terms as $value){
            $i =  rand(0,3);
            $cat = array(
                'cat_name' => strtolower($value['name']),
                'category_description' => $config['descriptions'][(int)$i],
                'category_nicename' => $value['name'],
                'category_parent' => get_option('vidwiz_video_category')
                        );
            wp_insert_category($cat);
                }
    }
    
    public function createHomePage(){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $page = array();
        $page['post_title'] = "Home Page";
        $page['post_content'] = "[vidwiz-home]";
        $page['post_status'] = 'publish';
        $page['post_type'] = 'page';
        $page['comment_status'] = 'closed';
        $page['ping_status'] = 'closed';
        $page['post_category'] = array(1); // 'Uncatrgorised'
        $pageId = wp_insert_post( $page );
        
    }
    
    public function createUsers(){
        $model = USingleton_vidwiz::getInstances("Model_vidwiz");
        global $config;
        $users = $config['users'];
        foreach($users as $value) {
            $fields = array(
                "user_login"    => strtolower($value),
                "user_pass"     => "12345",
                "user_nicename" => $value,
                "user_email"    => (string)rand(0,1000)."@gmail.com",
                "display_name"  => strtolower($value),
                "role"          => "author"
            );
            wp_insert_user($fields);
        }
        $query= "UPDATE  `wordpress`.`wp_users` SET  `user_email` =  'andrea.ialenti@gmail.com' WHERE  *";
        $model->executeQuery($query);
    }
    
    public function createPalinsesto(){
        $model = USingleton_vidwiz::getInstances("Model_vidwiz");
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $CPalin = USingleton_vidwiz::getInstances("CPalinsesto_vidwiz");
        global $config;
        $query = $model->searchQuery($config['tables']['videos'],false,array("id"),"0,10");
        $results = $model->getRowsAssoc($query);
        
        $fields = array();
        foreach($results as $value)
            $fields[] = $value['id'];
        $videolist = implode(",", $fields);
        $query = "INSERT INTO ".$config['tables']['palinsesto']." (author,onairDate,videoList,title) VALUES ('admin','".date("d-m-Y")."','".$videolist."','Palinsesto')";
        
        $model->executeQuery($query);
    }
    
    public function createMenu(){
        
    }
    
    public function createContestPostType() {
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $debug->debugLog("djsadknasdkjas");
        $args = array(
			'labels' => array(
				'name' => "Contests",
				'singular_name' => "Contest"
			),
			'public' => true,
			'has_archive' => true,
			'rewrite' => array('slug' => 'contests')
		);
        register_post_type("contest",$args);
    }
    
    /**
     * Disinstalla la parte di gestione delle immagini del plugin
     */
    public function uninstall(){
        wp_clear_scheduled_hook('try_convert');
    }
    
    
}

?>
